<template>
  <div class="flex flex_column">
    <!--选择物料 -->
    <el-dialog
      append-to-body
      title="选择物料"
      :visible.sync="isVisible"
      :close-on-click-modal="false"
      custom-class="bodyNoPadDialog bigDialog"
      width="85%"
      @close="closeMarDialog"
      @open="restData"
    >
      <div class="pupMain">
        <div class="pupTree">
          <div class="maerMange">
            <div class="cTitle">已选物料</div>
            <div>
              <ul>
                <li :class="classIndex === -1? 'on':''" @click="selectAll">
                  <i class="iconfont folderIco mr5 f22" /> {{ '已选物料' }}
                </li>
              </ul>
            </div>
            <div class="cTitle">全部物料</div>
            <div>
              <ul>
                <li :class="classIndex === -2? 'on':''" @click="AllMaterList">
                  <i class="iconfont folderIco mr5 f22" /> {{ '全部物料' }}
                </li>
              </ul>
            </div>
            <div class="cTitle">物料分组</div>
            <!-- 基础数据所有分组       -->
            <div class="materielList">
              <ul>
                <template v-for="(item,index) in allMaterielClass">
                  <li
                    :key="item.dictionaryID"
                    class="flex flex_between"
                    :class="classIndex === index? 'on':''"
                    @click="changeMaterClass(item,index)"
                  >
                    <div>
                      <i class="iconfont folderIco mr5 f22" style="color: #83A0FF;" /> {{ item.groupName }}({{ item.speciesStockQuantity }})
                    </div>
                  </li>
                </template>
              </ul>
            </div>
            <div v-if="allMaterielClass.length==0" class="p16">
              <el-skeleton :rows="10" animated />
            </div>
          </div>
        </div>
        <div class="pupContent">
          <!-- 操作区 S-->
          <div class="d_operationBox" style="padding:0 10px">
            <div class="d_btn">
              <h3>{{ subTitle }}({{ total || 0 }})</h3>
            </div>
            <div class="d_search" v-if="select === 'row'">
              <el-input
                v-model="materalSearch.likeWords"
                placeholder="物料编号/物料名称"
                size="small"
              >
                <el-button
                  slot="append"
                  :loading="marLoading"
                  type="primary"
                  icon="el-icon-search"
                  :disabled="marLoading"
                  element-loading-spinner="el-icon-loading"
                  @click="selectGroupList"
                >
                  搜索
                </el-button>
              </el-input>
            </div>
          </div>
          <!-- 操作区 E-->
          <!-- 表格区域       -->
          <div class="">
            <el-table
              v-show="select === 'all'"
              ref="allMultipleTable"
              :data="allMaterialList"
              border
              height="530px"
              style="width: 100%"
              @select="allHandleSelectionChange"
              @select-all="handleSelectRow"
            >
              <el-table-column
                type="selection"
                width="50"
              />
              <el-table-column prop="specificationCode" label="物料编号" />
              <el-table-column prop="goodsName" label="物料名称" />
              <el-table-column prop="stockGoodsName" label="规格型号" />
              <el-table-column prop="supplierName" width="200" show-overflow-tooltip label="供应商" />
              <el-table-column prop="categoryName" label="物料类型" />
              <el-table-column prop="goodsUnitName" label="单位" />
              <el-table-column prop="stockSumQuantity" label="库存数量" />
              <el-table-column prop="groupName" label="所属分组" />
            </el-table>
            <el-table
              v-show="select === 'row'"
              ref="multipleTable"
              :data="materialList"
              height="530px"
              border
              style="width: 100%"
              @select="handleSelectionChange"
              @select-all="handleSelectAll"
            >
              <el-table-column
                type="selection"
                width="55"
              />
              <el-table-column prop="specificationCode" label="物料编号" />
              <el-table-column prop="goodsName" label="物料名称" />
              <el-table-column prop="stockGoodsName" width="" label="规格型号" />
              <el-table-column prop="supplierName" width="200"  label="供应商" />
              <el-table-column prop="categoryName" label="物料类型" />
              <el-table-column prop="goodsUnitName" label="单位" />
              <el-table-column prop="stockSumQuantity" label="库存数量" />
              <el-table-column prop="groupName" label="所属分组" />
            </el-table>
          </div>
        </div>
      </div>
      <div slot="footer" class="dialog-footer">
        <el-button size="mini" @click="isVisible = false">取 消</el-button>
        <!-- 选择订单 -->
        <el-button
          :loading="addLoading"
          :disabled="addLoading"
          element-loading-spinner="el-icon-loading"
          type="primary"
          size="mini"
          @click="saveColorManuscript"
        >
          确定</el-button>
      </div>
    </el-dialog>
  </div>
</template>
<script>
export default {
  name: 'SelectMateriaList',
  props: {
    perVisible: {
      type: Boolean,
      required: false
    },
    selectCode: {
      type: String,
      default: ''
    },
    selectList: {
      type: Array,
      default: () => {
        return []
      }
    }
  },
  data() {
    return {
      materialList: [], // 单个物料列表
      allMaterialList: [], // 已选物料列表
      templateSelection: {},
      radio: '',
      subTitle: '全部物料',
      materalSearch: {
        likeWords: '',
        groupCode: '',
        categoryCode: ''
      }, // 列表明细搜索条件
      radioSelect: null,
      currentRow: null,
      marLoading: false,
      addLoading: false,
      total: 0,
      classIndex: -2, // 选中分组索引
      select: 'row', // all 已选物料 row 物料分组
      selectGroupCode: '', // 选中物料code
      multipleSelection: [],
      allMaterielClass: [],
      copyList: []
    }
  },
  computed: {
    isVisible: {
      get() {
        return this.perVisible
      },
      set(val) {
        this.$emit('update:perVisible', val)
      }
    }
  },
  created() {
    this.allMaterialList = this.allMaterialList.concat(this.selectList)
    this.getMatchGoodsGroups()
  },
  mounted() {

  },
  methods: {
    // 弹框打开时刷新物料列表
    restData() {
      this.materalSearch.likeWords = ''
      this.allMaterialList = []
      this.allMaterialList = this.allMaterialList.concat(this.selectList)
      this.getMatchGoodsGroups()
    },
    closeMarDialog() {
      this.isVisible = false
    },
    // 已选物料
    selectAll() {
      this.select = 'all'
      this.classIndex = -1
      this.subTitle = '已选物料'
      this.total = this.allMaterialList.length
      this.allMaterialList.forEach((rows) => {
        if (rows) {
          this.$refs.allMultipleTable.toggleRowSelection(rows, true)
        }
      })
    },
    AllMaterList() {
      this.select = 'row'
      this.subTitle = '全部物料'
      this.classIndex = -2
      this.materalSearch.groupCode = ''
      this.materalSearch.categoryCode = ''
      this.selectGroupList()
    },
    changeMaterClass(item, index) {
      this.select = 'row'
      this.classIndex = index
      this.materalSearch.groupCode = item.groupCode
      this.selectGroupCode = item.groupCode
      this.subTitle = item.groupName
      this.selectGroupList()
    },
    // 已经选择改变
    handleSelectionChange(selection, row) {
      // isExited判断selected是否已经存在当前项
      let isExited = false
      this.allMaterialList.forEach(item => {
        if (item.stockGoodsID === row.stockGoodsID) {
          isExited = true
        }
      })
      if (isExited) {
        // 若存在，代表操作是 取消选中
        this.handleDelRowItem(row)
      } else {
        // 反之，选中某项
        this.allMaterialList.push(row)
      }
    },
    handleSelectAll(selection) {
      if (selection.length > 0) {
        this.copyList = JSON.parse(JSON.stringify(selection))
      }
      if (selection.length === 0) {
        this.copyList.forEach(item => {
          this.handleDelAllItem(item)
        })
      } else {
        const _arr = this.allMaterialList.concat(selection)
        const obj = {}
        this.allMaterialList = _arr.reduce((cur, next) => {
          obj[next.stockGoodsID] ? '' : obj[next.stockGoodsID] = true && cur.push(next)
          return cur
        }, [])
      }
    },
    handleSelectRow(selection) {
      if (selection.length === 0) {
        this.allMaterialList = []
      }
    },
    handleDelRowItem(row) {
      let index = -1
      this.allMaterialList.forEach((item, idx) => {
        if (item.stockGoodsID === row.stockGoodsID) {
          index = idx
        }
      })
      if (index >= 0) {
        this.allMaterialList.splice(index, 1)
      }
    },
    handleDelAllItem(row) {
      const index = this.allMaterialList.findIndex((x) => {
        return x.stockGoodsID === row.stockGoodsID
      })
      this.allMaterialList.splice(index, 1)
      this.selectOne()
    },
    // 所有已选改变
    allHandleSelectionChange(selection, row) {
      this.handleDelAllItem(row)
    },
    selectOne() {
      this.materialList.forEach(m => {
        if (m && this.$refs.multipleTable) {
          const checked = this.allMaterialList.some((item) => item.stockGoodsID === m.stockGoodsID)
          if (checked) {
            this.$nextTick(() => {
              this.$refs.multipleTable.toggleRowSelection(m, true)
            })
          } else {
            this.$nextTick(() => {
              this.$refs.multipleTable.toggleRowSelection(m, false)
            })
          }
        }
      })
    },
    // 获取物料分组
    getMatchGoodsGroups() {
      this.$api.product
        .GetMatchGoodsGroups({
          likeWords: ''
        })
        .then((res) => {
          this.allMaterielClass = res
          // this.materalSearch.groupCode = res[0].groupCode
          this.selectGroupList()
        })
        .catch(() => {})
    },
    open() {
      this.isVisible = true
      this.selectGroupList()
    },
    // 列表
    selectGroupList() {
      const parmas = this.materalSearch
      this.marLoading = true
      this.$api.product
        .GetMatchStockGoodsDataList(parmas)
        .then((res) => {
          this.materialList = res
          this.total = res.length
          this.marLoading = false
          this.selectOne()
        })
        .catch(() => {})
    },
    saveColorManuscript() {
      if (this.allMaterialList.length > 0) {
        this.$emit('getMateriListData', this.allMaterialList)
        this.isVisible = false
      } else {
        this.$message({
          message: '请选择物料',
          type: 'error'
        })
      }
    }
  }
}
</script>
<style lang="scss" scoped>

.container {
  height: 100%;
}
.navTT {
  line-height: 22px;
  padding: 16px;
}
.permangeRg {
  border: 1px solid #e6e6e6;
  background: #fff;
  height: 100%;

  .mainTT {
    font-size: 16px;
    font-weight: bold;
    width: 100%;
    padding-bottom: 0;
  }
}
.pupTree {
  width: 220px;
  .kuOP {
    display: none;
  }
  ul{
    margin: 0 -16px;
  }
  li {
    padding:8px 16px;
    cursor: pointer;
    &:hover {
      background: #3f61f110;
      color: #3f61f1;

      .kuOP {
        display: block !important;
      }
    }
  }
  li.on {
    background: #3f61f110;
    color: #3f61f1;
  }
  .allMateriel {
    line-height: 44px;
    padding-left: 16px;
    &:hover {
      background: #3f61f110;
      color: #3f61f1;
    }
  }
  .allMateriel.crt {
    background: #3f61f110;
    color: #3f61f1;
  }
}
</style>
